package com.qf.security;

import com.qf.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @date 2025/5/8
 * @desc
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取token
        String token = jwtUtils.getToken(request);
        // 如果token不为空，且认证信息为空,即没有认证信息时再解析token
        Authentication authentication = SecurityContextHolder.getContext( ).getAuthentication( );
        log.debug("JwtAuthenticationTokenFilter 类中的认证对象authentication: {}", authentication);
        if (!ObjectUtils.isEmpty(token) && authentication == null) {
            // 验证token,如果token验证失败，则抛出异常,后续不再执行
            jwtUtils.validateToken(token);

            // 如果验证成功,则刷新令牌时间
            jwtUtils.refreshToken(token);

            // 解析token,获取用户信息
            Claims claims = jwtUtils.parseJWT(token);
            List<String> authorities = claims.get("perms", List.class);
            // 字符串使用指定的符号拼接成一个完整的字符串
            String authoritiesString = String.join(",", authorities);
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(claims.get("username"),
                            null,
                            AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesString));
            authenticationToken.setDetails(new WebAuthenticationDetailsSource( ).buildDetails(request));
            // 放入上下文
            SecurityContextHolder.getContext( ).setAuthentication(authenticationToken);

        }
        filterChain.doFilter(request, response);
    }
}
